package pro.softzhang.algo.lc700;

import com.alibaba.fastjson.JSON;
import pro.softzhang.algo.flag.difficulty.DRed;

import java.util.Stack;

/**
 *
 */
@DRed
public class LC735_AsteroidCollision {
    public static void main(String[] args) {
        int[] asteroids = {5, 10, -5};
        int[] res = new Solution().asteroidCollision(asteroids);
        System.out.println(JSON.toJSONString(res));
    }

    static class Solution {
        public int[] asteroidCollision(int[] asteroids) {
            Stack<Integer> stack = new Stack<>();
            for (int asteroid : asteroids) {
                while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -asteroid) {
                    stack.pop();
                }
                if(!stack.empty() && asteroid < 0 && stack.peek() == -asteroid) {
                    stack.pop();
                    continue;
                }
                if(asteroid > 0 || stack.empty() || stack.peek() < 0) {
                    stack.push(asteroid);
                }
            }
            return stack.stream().mapToInt(i -> i).toArray();
        }
    }
}